<template>
  <div>
    <BasicTable @register="registerTable" @edit-change="handleEditChange">
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '删除',
              onClick: handleDelete.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <a-button block class="mt-5" type="dashed" @click="openPracticeAdd"> 新增做法 </a-button>
    <PracticeAddModal @register="registerPracticeAddModal" @selectRowList="handleSelectRowList" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, toRefs, watch } from 'vue';
  import { columns } from './practice.data';
  import { BasicTable, EditRecordRow, TableAction, useTable } from '/@/components/Table';
  import { getListAll } from '/@/api/cuisine/cuisinePractice';
  import PracticeAddModal from './popup/PracticeAddModal.vue';
  import { useModal } from '/@/components/Modal';

  export default defineComponent({
    components: { BasicTable, TableAction, PracticeAddModal },
    props: {
      cuisineId: { type: String },
    },
    setup(props) {
      const { cuisineId } = toRefs(props);

      watch(cuisineId, (newVal) => {
        if (newVal) {
          fetch(newVal);
        }
      });

      const cuisinePracticeData = ref<any[]>([]);

      async function fetch(cuisineId) {
        cuisinePracticeData.value = await getListAll({
          cuisineId,
        });
      }

      const [registerTable, { getDataSource }] = useTable({
        rowKey: 'practiceId',
        canResize: false,
        columns: columns,
        showIndexColumn: false,
        dataSource: cuisinePracticeData,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        pagination: false,
      });

      function handleDelete(record: EditRecordRow) {
        const data = getDataSource();
        const index = data.findIndex((item) => item.key === record.key);
        data.splice(index, 1);
      }

      const [registerPracticeAddModal, { openModal }] = useModal();
      function openPracticeAdd(record: Recordable) {
        console.log(record);
        openModal(true, {
          isUpdate: true,
        });
      }
      function handleSelectRowList(record: Recordable[]) {
        const data = getDataSource();
        const list = record.map((item) => {
          item.practiceId = item.id;
          item.id = null;
          return item;
        });
        data.push(...list);
      }
      return {
        registerTable,
        getDataSource,
        handleDelete,
        registerPracticeAddModal,
        openPracticeAdd,
        handleSelectRowList,
      };
    },
  });
</script>
